package com.vanysoft.framework.utils;

import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;

public class CommonUtil {


    /**
     * Function Name               removeRepeatCode
     *
     * @param mapList
     * @param columnName
     * @return
     * @description (将集合中的字符串集去重以逗号分割拼接成字符串)
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月4日 下午11:22:29          SharpClaw_x                     Initial
     * *********************************************************************
     */
    @SuppressWarnings("rawtypes")
    public static String removeRepeatCode(List<Map> mapList, String columnName) {
        String columnNameCodeList = "";
        if (mapList != null && mapList.size() > 0 && mapList.get(0) != null) {
            for (int i = 0; i < mapList.size(); i++) {
                columnNameCodeList = columnNameCodeList + mapList.get(i).get(columnName) + ",";
            }
            //截取掉最后一个逗号
            columnNameCodeList = columnNameCodeList.substring(0, columnNameCodeList.length() - 1);
        }

        return removeRepeatStr(columnNameCodeList);


    }


    /**
     * Function Name               removeRepeatStr
     *
     * @param columnNameCodeList
     * @return
     * @description 字符串去重
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月5日 下午9:13:56          SharpClaw_x                     Initial
     * 2017年6月14日 下午9:13:56  shuxl     修复
     * *********************************************************************
     */
    public static String removeRepeatStr(String columnNameCodeList) {
//		//取到机构代码集合去重
//		String[] columnGroup=columnNameCodeList.substring(0, columnNameCodeList.length()-1).split(",");
//		columnNameCodeList="";
//		for(int i=0;i<columnGroup.length;i++){
//			if(columnNameCodeList.indexOf(columnGroup[i])==-1){
//				columnNameCodeList=columnNameCodeList+columnGroup[i]+",";
//			}
//		}
//		columnNameCodeList=columnNameCodeList.substring(0, columnNameCodeList.length()-1);
        Set<String> codeSet = new HashSet<>();
        if (null != columnNameCodeList) {
            String[] codeArr = columnNameCodeList.split(",");
            for (String codeItem : codeArr) {
                if (StringUtils.isNotBlank(codeItem)) {
                    codeSet.add(codeItem);
                }
            }
        }

        return StringUtils.join(codeSet.toArray(), ",");
    }

    /**
     * Function Name               sendPost
     *
     * @param url
     * @return
     * @description 发送POST请求
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年8月25日 下午8:39:09          SharpClaw_x                     Initial
     * *********************************************************************
     */
    public static String sendPost(String url) {
        String result = "";
        try {
            URL httpurl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) httpurl
                    .openConnection();
            connection.setDoInput(true); // 允许输入流,默认是true，而doOutput -
            // 允许输出流,默认是false
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String encoding = connection.getContentEncoding();
            if ("gzip".equals(encoding)) {
                reader = new BufferedReader(new InputStreamReader(
                        new GZIPInputStream(connection.getInputStream()),
                        "UTF-8"));
            } else {
                reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), "UTF-8"));
            }
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("没有结果！" + e);
        }
        return result;
    }


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader reader = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-Type", "text/html; charset=utf-8");

            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
//            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String encoding = connection.getContentEncoding();
            if ("gzip".equals(encoding)) {
                reader = new BufferedReader(new InputStreamReader(
                        new GZIPInputStream(connection.getInputStream()),
                        "UTF-8"));
            } else {
                reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), "UTF-8"));
            }
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


    public static String formatDateStr(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.format(date);
        } catch (Exception e) {
            System.err.println("Exception caught: " + e.getMessage());
        }
        return null;
    }


    public static String formatTime(Calendar cal) {
        // 0/1 * * * * ?
        int year = cal.get(Calendar.YEAR);//获取年份
        int month = cal.get(Calendar.MONTH) + 1;//获取月份
        int day = cal.get(Calendar.DATE);//获取日
        int hour = cal.get(Calendar.HOUR_OF_DAY);//小时
        int minute = cal.get(Calendar.MINUTE);//分
        int second = cal.get(Calendar.SECOND);//秒
        String time = second + " " + minute + " " + hour + " " + day + " " + month + " ? " + year;//21 01 15 7 9 ? 2017

        return time;
    }


}
